package com.le.tester.book.concurrentchallenge.atomicnoblocking15;

import java.util.concurrent.atomic.AtomicReference;

/**
 * createTime：2025-05-25 10:30
 * description：使用cas来维持包含多个变量的不变性条件
 */
public class CASNumberRange {

    private static class IntPair {
        //        不变性条件：lower<=upper
        final int lower;
        final int upper;

        public IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }

        private final AtomicReference<IntPair> values =
                new AtomicReference<>(new IntPair(0, 0));

        public int getUpper() {
            return values.get().upper;
        }

        public int getLower() {
            return values.get().lower;
        }

        public void setLower(int i) {
            while (true) {
                IntPair oldV = values.get();
                if (i > oldV.upper) {
                    throw new IllegalArgumentException("can set lower to " + i + " > upper");
                }

                IntPair newV = new IntPair(i, oldV.upper);
                if (values.compareAndSet(oldV, newV)) {
                    return;
                }
            }
        }
    }
}
